package it.orma.iridehr.service;

import it.orma.iridehr.controllers.ricerca.RicercaForm;
import it.orma.iridehr.repository.CandidatoRepository;
import it.orma.iridehr.repository.RicercaRepository;
import it.orma.iridehr.services.helper.DocumentoAlfresco;
import it.orma.iridehr.services.helper.RisultatoRicerca;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.alfresco.cmis.client.AlfrescoAspects;
import org.alfresco.cmis.client.AlfrescoFolder;
import org.alfresco.webservice.util.ISO9075;
import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.DocumentType;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.apache.chemistry.opencmis.client.api.FolderType;
import org.apache.chemistry.opencmis.client.api.ItemIterable;
import org.apache.chemistry.opencmis.client.api.ObjectId;
import org.apache.chemistry.opencmis.client.api.ObjectType;
import org.apache.chemistry.opencmis.client.api.OperationContext;
import org.apache.chemistry.opencmis.client.api.QueryResult;
import org.apache.chemistry.opencmis.client.api.Repository;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.client.api.SessionFactory;
import org.apache.chemistry.opencmis.client.runtime.OperationContextImpl;
import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl;
import org.apache.chemistry.opencmis.commons.data.ContentStream;
import org.apache.chemistry.opencmis.commons.data.PropertyData;
import org.apache.chemistry.opencmis.commons.definitions.PropertyDefinition;
import org.apache.chemistry.opencmis.commons.enums.VersioningState;
import org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException;
import org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl;
import org.apache.chemistry.opencmis.commons.PropertyIds;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

public class AlfrescoService {

	private Map<String, String> cmisParameter;
	
	@Autowired 
	RicercaRepository ricercaRepository;

	public void setCmisParameter(Map<String, String> cmisParameter) {
		this.cmisParameter = cmisParameter;
	}

	private Session getCurrentSession() {
		SessionFactory sessionFactory = SessionFactoryImpl.newInstance();
		Repository repository = sessionFactory.getRepositories(cmisParameter)
				.get(0);
		return repository.createSession();
	}

	public List<RisultatoRicerca> ricercaDocumentiSuAlfresco(
			RicercaForm ricercaForm) {
		ricercaForm.setTipoRicerca("cercacandidatialfresco");
		Session session = getCurrentSession();
		List<RisultatoRicerca> risultati = new ArrayList<RisultatoRicerca>();
		OperationContext operationContext = new OperationContextImpl();
		// SELECT SCORE() sc, D.* FROM cmis:document D WHERE
		// CONTAINS('TEXT:pro*') order by sc desc

		StringBuilder builder = new StringBuilder();
		StringTokenizer tokenizer = new StringTokenizer(ricercaForm.getQuery().replaceAll(" +", " ")," ");
		while (tokenizer.hasMoreTokens()){
			builder.append(" CONTAINS(D,'*"+tokenizer.nextToken().replaceAll("\\\\","\\\\\\\\").replaceAll("\\.", "\\\\.").replaceAll("'","\\\\'")
					+"*') "+ricercaForm.getCriteria());
		}
		String query = builder.toString().substring(0,builder.toString().lastIndexOf(ricercaForm.getCriteria()));
				
		ItemIterable<QueryResult> results = session.query(
				"SELECT SCORE() sc,  D.cmis:objectId , D.cmis:name, t.cm:title FROM cmis:document as D join cm:titled as t on D.cmis:objectId = t.cmis:objectId WHERE " +
//				"CONTAINS('PATH:\"/app:company_home/st:sites/cm:orma-hr/cm:documentLibrary/cm:CV/cm:"+ISO9075.encode("2013")+"/cm:giugno/cm:"+ISO9075.encode("3")+"/*\"') AND "+
				"CONTAINS(D,'PATH:\"/app:company_home/st:sites/cm:orma-hr/cm:documentLibrary/cm:CV//.\"') AND "+
				"(".concat(
						query).concat(") order by sc desc"),
				false, operationContext);
		ricercaForm.setResultSize(new Long(results.getTotalNumItems())
				.intValue());
		results = results.skipTo(new Long(ricercaForm.getPagina()
				* ricercaForm.getRecordPerPagina()));
		results = results.getPage(ricercaForm.getRecordPerPagina());
		for (QueryResult queryResult : results) {
			RisultatoRicerca r = new RisultatoRicerca(null, queryResult
					.getPropertyValueById("cmis:objectId").toString(),
					queryResult.getPropertyValueById("cmis:name").toString(),
					null);
			r.setTitle(queryResult.getPropertyValueById("cm:title").toString());
			PropertyData scoreProperty = queryResult
					.getPropertyByQueryName("sc");
			Double score = Double.valueOf(scoreProperty.getFirstValue()
					.toString());
			r.setScore(score);
			PropertyData creationDate = queryResult
					.getPropertyById("cmis:creationDate");
			if (creationDate != null) {
				GregorianCalendar gc = (GregorianCalendar) creationDate
						.getFirstValue();
				r.setDataAggiornamento(gc.getTime());
			}
			if(r.getTitle().startsWith("CV_")){
				String email_opp = r.getTitle().substring(r.getTitle().indexOf("CV_")+3,r.getTitle().lastIndexOf("_"));
				String email = email_opp.substring(0,email_opp.lastIndexOf("_"));
				List<Object> res = ricercaRepository.ricercaLinkAlfrescoDB(email);
				if(res!=null&&res.size()>0){
					r.setIdSchedaCandidato(((BigInteger) res.get(0)).longValue());
				}else{
					r.setDbUnlinked(true);
					r.setEmail(email);
				}
			}else if(r.getTitle().startsWith("All_")){
				String email = r.getTitle().substring(r.getTitle().indexOf("All_")+4,r.getTitle().lastIndexOf("_"));
				List<Object> res = ricercaRepository.ricercaLinkAlfrescoDB(email);
				if(res!=null&&res.size()>0){
					r.setIdSchedaCandidato(((BigInteger) res.get(0)).longValue());
				}else{
					r.setDbUnlinked(true);
					r.setEmail(email);
				}
			}
			risultati.add(r);
		}

		return risultati;
	}
	
	public List<RisultatoRicerca> ricercaCandidatoSuAlfresco(String email,String tipo) {

		Session session = getCurrentSession();
		List<RisultatoRicerca> risultati = new ArrayList<RisultatoRicerca>();
		OperationContext operationContext = new OperationContextImpl();
		// SELECT SCORE() sc, D.* FROM cmis:document D WHERE
		// CONTAINS('TEXT:pro*') order by sc desc
	
			final String sites = "/Sites";
			Session alfrescoSession = getCurrentSession();
			
			String cvFolder = "cm:CV";
			
			String PATTERN = "^[A-Za-z]$";
	    	Pattern pattern = 
	        Pattern.compile(PATTERN);

	        Matcher matcher = pattern.matcher(email.substring(0,1));
	    	if (!matcher.matches()){

	    		cvFolder += "/Altro/"+ISO9075.encode(email)+"/"+tipo;

	    	}else{
	    		
	    			cvFolder += "/cm:"+email.substring(0,1).toUpperCase();
	    			
	    			PATTERN = "^[A-Ma-m]$";
	    			pattern = Pattern.compile(PATTERN);

	    			matcher = pattern.matcher(email.substring(1,2));
	    			if (matcher.matches()){
	    				cvFolder += "/cm:"+email.substring(0,1).toUpperCase()+"A_"+
								email.substring(0,1).toUpperCase()+"M/cm:"+ISO9075.encode(email)+"/cm:"+tipo;
						
	    			}else{
	    				PATTERN = "^[N-Zn-z]$";
	    				pattern = Pattern.compile(PATTERN);

	    				matcher = pattern.matcher(email.substring(1,2));
	    				if (matcher.matches()){
	    					cvFolder += "/cm:"+email.substring(0,1).toUpperCase()+"N_"+
									email.substring(0,1).toUpperCase()+"Z/cm:"+ISO9075.encode(email)+"/cm:"+tipo;
							
		    				
	    				}else{
	    					
	    					cvFolder += "/cm:Altro/cm:"+ISO9075.encode(email)+"/cm:"+tipo;							
		    				
	    			}
	    		}
	    	}

		StringBuilder builder = new StringBuilder();
		
		ItemIterable<QueryResult> results = session.query(
				" SELECT   D.cmis:objectId , D.cmis:name, t.cm:title FROM cmis:document as D join cm:titled as t on D.cmis:objectId = t.cmis:objectId WHERE "+
//				"CONTAINS('PATH:\"/app:company_home/st:sites/cm:orma-hr/cm:documentLibrary/cm:CV/cm:"+ISO9075.encode("2013")+"/cm:giugno/cm:"+ISO9075.encode("3")+"/*\"') AND "+
				"CONTAINS(D,'PATH:\"/app:company_home/st:sites/cm:orma-hr/cm:documentLibrary/"+cvFolder+"//.\"')",
				false, operationContext);
		
		for (QueryResult queryResult : results) {
			RisultatoRicerca r = new RisultatoRicerca(null, queryResult
					.getPropertyValueById("cmis:objectId").toString(),
					queryResult.getPropertyValueById("cmis:name").toString(),
					null);
			r.setTitle(queryResult.getPropertyValueById("cm:title").toString());
			PropertyData creationDate = queryResult.getPropertyById("cmis:creationDate");
			if (creationDate != null) {
				GregorianCalendar gc = (GregorianCalendar) creationDate
						.getFirstValue();
				r.setDataAggiornamento(gc.getTime());
			}
			
			risultati.add(r);
		}

		return risultati;
	}

	public DocumentoAlfresco estraiTestoDalDocumento(String id)
			throws IOException {
		Session session = getCurrentSession();
		Document document = (Document) session.getObject(id);
		DocumentoAlfresco documentoAlfresco = new DocumentoAlfresco();
		documentoAlfresco.setContentLenght(document.getContentStreamLength());
		documentoAlfresco.setContentType(document.getContentStreamMimeType());
		documentoAlfresco.setFileName(document.getContentStreamFileName());
		documentoAlfresco.setStream(document.getContentStream().getStream());
		return documentoAlfresco;
	}
	
	public Document getDocument(String objectId){
		Session session = getCurrentSession();
		Document document = (Document) session.getObject(objectId);
		return document;
	}
	
	public Document getDocumentWithName(String nome){
		Session session = getCurrentSession();
		ObjectType type = session.getTypeDefinition("hr:document");
		PropertyDefinition<?> objectIdPropDef = type.getPropertyDefinitions()
				.get(PropertyIds.OBJECT_ID);
		String objectIdQueryName = objectIdPropDef.getQueryName();

		ItemIterable<QueryResult> results = session.query(
				"SELECT * FROM hr:document WHERE cmis:name='" + nome
						+ "'", false);
		for (QueryResult qResult : results) {
			String objectId = qResult
					.getPropertyValueByQueryName(objectIdQueryName);
			return (Document) session.getObject(session.createObjectId(objectId));
		}
		return null;
	}

	public Folder getFolder(String folderName) {
		Session session = getCurrentSession();
		ObjectType type = session.getTypeDefinition("cmis:folder");
		PropertyDefinition<?> objectIdPropDef = type.getPropertyDefinitions()
				.get(PropertyIds.OBJECT_ID);
		String objectIdQueryName = objectIdPropDef.getQueryName();

		ItemIterable<QueryResult> results = session.query(
				"SELECT * FROM cmis:folder WHERE cmis:name='" + folderName
						+ "'", false);
		for (QueryResult qResult : results) {
			String objectId = qResult
					.getPropertyValueByQueryName(objectIdQueryName);
			return (Folder) session.getObject(session.createObjectId(objectId));
		}
		return null;
	}
	
	public Folder getFolderWithId(String id) {
		Session session = getCurrentSession();
		ObjectType type = session.getTypeDefinition("cmis:folder");
		PropertyDefinition<?> objectIdPropDef = type.getPropertyDefinitions()
				.get(PropertyIds.OBJECT_ID);
		String objectIdQueryName = objectIdPropDef.getQueryName();

		ItemIterable<QueryResult> results = session.query(
				"SELECT * FROM cmis:folder WHERE cmis:objectId='" + id
						+ "'", false);
		for (QueryResult qResult : results) {
			String objectId = qResult
					.getPropertyValueByQueryName(objectIdQueryName);
			return (Folder) session.getObject(session.createObjectId(objectId));
		}
		return null;
	}

	/**
	 * Creates a folder under the given parent folder.
	 */
	public Folder createFolder(Folder parentFolder,
			String folderName) {
		Session session = getCurrentSession();
		Map<String, Object> folderProps = new HashMap<String, Object>();
		folderProps.put(PropertyIds.NAME, folderName);
		folderProps.put(PropertyIds.OBJECT_TYPE_ID,
				FolderType.FOLDER_BASETYPE_ID);

		ObjectId folderObjectId = session.createFolder(folderProps,
				parentFolder, null, null, null);
		return (Folder) session.getObject(folderObjectId);
	}

	/**
	 * Creates a document with the given content in a certain folder.
	 */
	public Document createDocument(Folder folder,
			String fileName, byte[] content, Map<String,Object> otherProps, String mimeType) throws Exception {
		Session session = getCurrentSession();
		Map<String, Object> docProps = new HashMap<String, Object>();
		docProps.put(PropertyIds.NAME, fileName);
		docProps.put(PropertyIds.OBJECT_TYPE_ID,"D:hr:document");
		docProps.putAll(otherProps);
		ByteArrayInputStream in = new ByteArrayInputStream(content);
		ContentStream contentStream = session.getObjectFactory()
				.createContentStream(fileName, content.length, mimeType, in);

		ObjectId documentId = session.createDocument(docProps, session
				.createObjectId((String) folder
						.getPropertyValue(PropertyIds.OBJECT_ID)),
				contentStream, null, null, null, null);
		Document document = (Document) session.getObject(documentId);
		return document;
	}

	public Folder getFolderByPath(String name) throws CmisObjectNotFoundException{
		Session session = getCurrentSession();
		Folder folder = (Folder) session.getObjectByPath(name);
				
		return folder;
	}
	
	public String storeCV(String email,String extension,String name,String title,
			ByteArrayOutputStream baos,String tipo) {

		final String sites = "/Sites";
		Session alfrescoSession = getCurrentSession();
		
		Folder cvFolder = (Folder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV");
		
		
		AlfrescoFolder mainLetterFolder = null;
		AlfrescoFolder mainRangeFolder = null;
		AlfrescoFolder emailFolder = null;
		AlfrescoFolder emailCVFolder = null;
		AlfrescoFolder emailAllFolder = null;
		String PATTERN = "^[A-Za-z]$";
    	Pattern pattern = 
        Pattern.compile(PATTERN);

        Matcher matcher = pattern.matcher(email.substring(0,1));
    	if (!matcher.matches()){
           
			try
			{
				mainLetterFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/Altro");
				System.out.println("Cartella Altro trovata...");
			}
			catch(CmisObjectNotFoundException ex)
			{
				System.out.println("Cartella anno non trovata la creo...");
				Map<String, Object> folderProperties = new HashMap<String, Object>();
				folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
				folderProperties.put(PropertyIds.NAME, "Altro");
				mainLetterFolder = (AlfrescoFolder) cvFolder.createFolder(folderProperties);
				System.out.println("Fatto");
			}
			try
			{
				emailFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/Altro/"+email);
				System.out.println("Cartella candidato trovata...");
			}
			catch(CmisObjectNotFoundException ex)
			{
				System.out.println("Cartella anno non trovata la creo...");
				Map<String, Object> folderProperties = new HashMap<String, Object>();
				folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
				folderProperties.put(PropertyIds.NAME, email);
				emailFolder = (AlfrescoFolder) mainLetterFolder.createFolder(folderProperties);
				System.out.println("Fatto");
			}
			try
			{
				emailCVFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/Altro/"+email+"/CV");
				
			}
			catch(CmisObjectNotFoundException ex)
			{
				System.out.println("Cartella CV candidato non trovata la creo...");
				Map<String, Object> folderProperties = new HashMap<String, Object>();
				folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
				folderProperties.put(PropertyIds.NAME, "CV");
				emailCVFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
				System.out.println("Fatto");
			}
			try
			{
				emailAllFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/Altro/"+email+"/Allegati");
				System.out.println("Cartella giorno trovata...");
			}
			catch(CmisObjectNotFoundException ex)
			{
				System.out.println("Cartella giorno non trovata la creo...");
				Map<String, Object> folderProperties = new HashMap<String, Object>();
				folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
				folderProperties.put(PropertyIds.NAME, "Allegati");
				emailAllFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
				System.out.println("Fatto");
			}
    	}else{
    		try
			{
				mainLetterFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+email.substring(0,1).toUpperCase());
				System.out.println("Cartella candidato trovata...");
			}
			catch(CmisObjectNotFoundException ex)
			{
				System.out.println("Cartella anno non trovata la creo...");
				Map<String, Object> folderProperties = new HashMap<String, Object>();
				folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
				folderProperties.put(PropertyIds.NAME, email.substring(0,1).toUpperCase());
				mainLetterFolder = (AlfrescoFolder) cvFolder.createFolder(folderProperties);
				System.out.println("Fatto");
			}
    		PATTERN = "^[A-Ma-m]$";
        	pattern = Pattern.compile(PATTERN);

            matcher = pattern.matcher(email.substring(1,2));
        	if (matcher.matches()){
				try
				{
					mainRangeFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+
							email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"A_"+
							email.substring(0,1).toUpperCase()+"M");
					System.out.println("Cartella main range...");
				}
				catch(CmisObjectNotFoundException ex)
				{
					System.out.println("Cartella anno non trovata la creo...");
					Map<String, Object> folderProperties = new HashMap<String, Object>();
					folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
					folderProperties.put(PropertyIds.NAME, email.substring(0,1).toUpperCase()+"A_"+
							email.substring(0,1).toUpperCase()+"M");
					mainRangeFolder = (AlfrescoFolder) mainLetterFolder.createFolder(folderProperties);
					System.out.println("Fatto");
				}
				try
				{
					emailFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/" +
							email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"A_"+
							email.substring(0,1).toUpperCase()+"M/"+email);
					System.out.println("Cartella candidato trovata...");
				}
				catch(CmisObjectNotFoundException ex)
				{
					System.out.println("Cartella anno non trovata la creo...");
					Map<String, Object> folderProperties = new HashMap<String, Object>();
					folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
					folderProperties.put(PropertyIds.NAME, email);
					emailFolder = (AlfrescoFolder) mainRangeFolder.createFolder(folderProperties);
					System.out.println("Fatto");
				}
				try
				{
					emailCVFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"A_"+
							email.substring(0,1).toUpperCase()+"M/"+email+"/CV");
					
				}
				catch(CmisObjectNotFoundException ex)
				{
					System.out.println("Cartella CV candidato non trovata la creo...");
					Map<String, Object> folderProperties = new HashMap<String, Object>();
					folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
					folderProperties.put(PropertyIds.NAME, "CV");
					emailCVFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
					System.out.println("Fatto");
				}
				try
				{
					emailAllFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"A_"+
							email.substring(0,1).toUpperCase()+"M/"+email+"/Allegati");
					System.out.println("Cartella allegati trovata...");
				}
				catch(CmisObjectNotFoundException ex)
				{
					System.out.println("Cartella giorno non trovata la creo...");
					Map<String, Object> folderProperties = new HashMap<String, Object>();
					folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
					folderProperties.put(PropertyIds.NAME, "Allegati");
					emailAllFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
					System.out.println("Fatto");
				}
        	}else{
        		PATTERN = "^[N-Zn-z]$";
            	pattern = Pattern.compile(PATTERN);

                matcher = pattern.matcher(email.substring(1,2));
            	if (matcher.matches()){
					try
					{
						mainRangeFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+
								email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"N_"+
								email.substring(0,1).toUpperCase()+"Z");
						System.out.println("Cartella main range...");
					}
					catch(CmisObjectNotFoundException ex)
					{
						System.out.println("Cartella anno non trovata la creo...");
						Map<String, Object> folderProperties = new HashMap<String, Object>();
						folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
						folderProperties.put(PropertyIds.NAME, email.substring(0,1).toUpperCase()+"N_"+
								email.substring(0,1).toUpperCase()+"Z");
						mainRangeFolder = (AlfrescoFolder) mainLetterFolder.createFolder(folderProperties);
						System.out.println("Fatto");
					}
					try
					{
						emailFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/" +
								email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"N_"+
								email.substring(0,1).toUpperCase()+"Z/"+email);
						System.out.println("Cartella candidato trovata...");
					}
					catch(CmisObjectNotFoundException ex)
					{
						System.out.println("Cartella anno non trovata la creo...");
						Map<String, Object> folderProperties = new HashMap<String, Object>();
						folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
						folderProperties.put(PropertyIds.NAME, email);
						emailFolder = (AlfrescoFolder) mainRangeFolder.createFolder(folderProperties);
						System.out.println("Fatto");
					}
					try
					{
						emailCVFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"N_"+
								email.substring(0,1).toUpperCase()+"Z/"+email+"/CV");
						
					}
					catch(CmisObjectNotFoundException ex)
					{
						System.out.println("Cartella CV candidato non trovata la creo...");
						Map<String, Object> folderProperties = new HashMap<String, Object>();
						folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
						folderProperties.put(PropertyIds.NAME, "CV");
						emailCVFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
						System.out.println("Fatto");
					}
					try
					{
						emailAllFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+email.substring(0,1).toUpperCase()+"/"+email.substring(0,1).toUpperCase()+"N_"+
								email.substring(0,1).toUpperCase()+"Z/"+email+"/Allegati");
						System.out.println("Cartella allegati trovata...");
					}
					catch(CmisObjectNotFoundException ex)
					{
						System.out.println("Cartella giorno non trovata la creo...");
						Map<String, Object> folderProperties = new HashMap<String, Object>();
						folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
						folderProperties.put(PropertyIds.NAME, "Allegati");
						emailAllFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
						System.out.println("Fatto");
					}
        		}else{
        			try
					{
						mainRangeFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+
								email.substring(0,1).toUpperCase()+"/Altro");
						System.out.println("Cartella main range...");
					}
					catch(CmisObjectNotFoundException ex)
					{
						System.out.println("Cartella anno non trovata la creo...");
						Map<String, Object> folderProperties = new HashMap<String, Object>();
						folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
						folderProperties.put(PropertyIds.NAME, "Altro");
						mainRangeFolder = (AlfrescoFolder) mainLetterFolder.createFolder(folderProperties);
						System.out.println("Fatto");
					}
        			try
					{
						emailFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/" +
								email.substring(0,1).toUpperCase()+"/Altro/"+email);
						System.out.println("Cartella candidato trovata...");
					}
					catch(CmisObjectNotFoundException ex)
					{
						System.out.println("Cartella anno non trovata la creo...");
						Map<String, Object> folderProperties = new HashMap<String, Object>();
						folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
						folderProperties.put(PropertyIds.NAME, email);
						emailFolder = (AlfrescoFolder) mainRangeFolder.createFolder(folderProperties);
						System.out.println("Fatto");
					}
        			try
					{
						emailCVFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+email.substring(0,1).toUpperCase()+"/Altro/"+email+"/CV");
						
					}
					catch(CmisObjectNotFoundException ex)
					{
						System.out.println("Cartella CV candidato non trovata la creo...");
						Map<String, Object> folderProperties = new HashMap<String, Object>();
						folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
						folderProperties.put(PropertyIds.NAME, "CV");
						emailCVFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
						System.out.println("Fatto");
					}
					try
					{
						emailAllFolder = (AlfrescoFolder) alfrescoSession.getObjectByPath(sites+"/orma-hr/documentLibrary/CV/"+email.substring(0,1).toUpperCase()+"/Altro/"+email+"/Allegati");
						System.out.println("Cartella allegati trovata...");
					}
					catch(CmisObjectNotFoundException ex)
					{
						System.out.println("Cartella giorno non trovata la creo...");
						Map<String, Object> folderProperties = new HashMap<String, Object>();
						folderProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
						folderProperties.put(PropertyIds.NAME, "Allegati");
						emailAllFolder = (AlfrescoFolder) emailFolder.createFolder(folderProperties);
						System.out.println("Fatto");
					}
        		}
        		}
        	
        	}
			
			Map<String, Object> fileProperties = new HashMap<String, Object>();
			fileProperties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document,P:cm:titled");
			fileProperties.put("cm:title", title);
			//fileProperties.put("cm:description", "My document");
			fileProperties.put(PropertyIds.NAME, name);
			
		//	MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
//					mimeTypesMap.addMimeTypes("application/pdf");
//					mimeTypesMap.addMimeTypes("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
			// only by file name
			
			String mimeType = determineMimeType(extension);
			
			ContentStream contentStream = new ContentStreamImpl(name,new BigInteger(baos.toByteArray()),mimeType,new ByteArrayInputStream(baos.toByteArray()));
			System.out.println("Carico il file...");
			
			Document newDoc = null;
			if (tipo.equals("All"))
				newDoc = emailAllFolder.createDocument(fileProperties, contentStream, VersioningState.MAJOR);
			else
				newDoc = emailCVFolder.createDocument(fileProperties, contentStream, VersioningState.MAJOR);
			return newDoc.getId();
		}
	
	private String determineMimeType(String extension) {
		
		String mimeType = "application/octet-stream";//mimeTypesMap.getContentType(fileName);
		if(extension.equals("pdf"))
		{
			mimeType ="application/pdf";
		}
//		else if(extension.equals("doc"))
//		{
//			mimeType ="application/vnd.openxmlformats-officedocument.wordprocessingml.document";
//		}
//		else if(extension.equals("docx"))
//		{
//			mimeType ="application/vnd.openxmlformats-officedocument.wordprocessingml.document";
//		}
		else if(extension.equals("xlsx"))
		{
			mimeType ="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
		}
		else if(extension.equals("xls"))
		{
			mimeType ="application/msexcel";
		}
		else if(extension.equals("pptx"))
		{
			mimeType ="application/vnd.openxmlformats-officedocument.presentationml.presentation";
		}
		else if(extension.equals("txt"))
		{
			mimeType ="application/text";
		}
		else if(extension.equals("doc"))
		{
			mimeType ="application/msword";
		}
		
		
		System.out.println("Tipo del file "+extension);
		return mimeType;
	}

	
	
	
}
